package com.hy.study.utils;

import java.util.Iterator;
import java.util.List;

/**
 * 分页查询的迭代器
 *
 * @author huyong
 * @date 2024 年 01 月 15 日 11:49: 11
 */
public abstract class PageIterator<T> implements Iterator<T> {
    private int start = 0;
    private int size = 5;//每页的大小
    private int currentIndex;
    private boolean hasMore = true;
    private List<T> list;

    public PageIterator(int size) {
        this.size=size;
    }

    @Override
    public boolean hasNext() {
        if (list != null && list.size() > currentIndex) {
            return true;
        }
        // 当前的数据已经加载完毕，尝试加载下一批
        if (!hasMore) {
            return false;
        }
        list = load(start, size);
        if (list == null || list.isEmpty()) {
        // 没有加载到数据，结束
            return false;
        }
        if (list.size() < size) {//最后一页返回数量比每页数量少
            hasMore = false;
        }
        currentIndex = 0;
        start += list.size();
        return true;
    }

    @Override
    public T next() {
        return list.get(currentIndex++);
    }
    public abstract List<T> load(int start, int size);
}
